<template>
  <div class="product-list-container">
    <!-- 头部搜索 -->
    <div class="search-header">
      <van-search
        v-model="searchForm.name"
        placeholder="搜索商品"
        shape="round"
        @search="onSearch"
        @clear="onSearch"
      />
    </div>

    <!-- 分类和筛选 -->
    <div class="filter-bar">
      <div class="filter-item" @click="showCategory = true">
        <span>{{ activeCategoryText }}</span>
        <van-icon name="arrow-down" />
      </div>
      <div class="filter-item" @click="sortProducts(1)">
        <span :class="{ active: sortType === 1 }">积分</span>
        <van-icon
          :name="sortType === 1 ? (sortOrder === 'asc' ? 'arrow-up' : 'arrow-down') : 'arrow'"
        />
      </div>
      <div class="filter-item" @click="sortProducts(2)">
        <span :class="{ active: sortType === 2 }">上架时间</span>
        <van-icon
          :name="sortType === 2 ? (sortOrder === 'asc' ? 'arrow-up' : 'arrow-down') : 'arrow'"
        />
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多商品了"
          @load="onLoad"
        >
          <div class="product-grid">
            <div
              class="product-card"
              v-for="product in productList"
              :key="product.id"
              @click="goToProductDetail(product.id)"
            >
              <img :src="product.image || defaultImage" class="product-img" />
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-price">{{ product.price }} 积分</div>
                <div class="product-action">
                  <van-button
                    type="primary"
                    size="mini"
                    icon="cart-o"
                    @click.stop="addToCart(product)"
                  >加入购物车</van-button>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 分类选择弹出层 -->
    <van-popup v-model:show="showCategory" position="top" :style="{ height: '40%' }" round>
      <div class="category-popup">
        <div class="popup-title">选择分类</div>
        <div class="category-list">
          <div
            class="category-item"
            :class="{ active: searchForm.category === '' }"
            @click="selectCategory('')"
          >全部商品</div>
          <div
            class="category-item"
            v-for="category in categories"
            :key="category"
            :class="{ active: searchForm.category === category }"
            @click="selectCategory(category)"
          >{{ category }}</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getProductList } from '@/api/product'
import { useCartStore } from '@/stores/cart'
import { showToast } from 'vant'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()

// 默认图片
const defaultImage = 'https://img01.yzcdn.cn/vant/apple-1.jpg'

// 分类
const categories = ref(['数码', '食品', '服装', '家居'])
const showCategory = ref(false)

// 搜索表单
const searchForm = reactive({
  name: (route.query.keyword as string) || '',
  category: '',
  page: 1,
  limit: 10,
})

// 排序相关
const sortType = ref(0) // 0: 默认, 1: 积分, 2: 上架时间
const sortOrder = ref('desc') // asc: 升序, desc: 降序

// 计算活动分类显示文本
const activeCategoryText = computed(() => {
  return searchForm.category || '全部商品'
})

// 商品列表
const productList = ref<any[]>([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const total = ref(0)

// 搜索
const onSearch = () => {
  searchForm.page = 1
  productList.value = []
  finished.value = false
  onLoad()
}

// 选择分类
const selectCategory = (category: string) => {
  searchForm.category = category
  showCategory.value = false
  onSearch()
}

// 排序商品
const sortProducts = (type: number) => {
  if (sortType.value === type) {
    // 切换排序方向
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    // 切换排序字段
    sortType.value = type
    sortOrder.value = 'desc'
  }

  onSearch()
}

// 加载商品
const onLoad = async () => {
  if (refreshing.value) {
    productList.value = []
    refreshing.value = false
  }

  loading.value = true

  try {
    // 构建排序参数
    let sortField = ''
    if (sortType.value === 1) {
      sortField = 'price' // 积分排序
    } else if (sortType.value === 2) {
      sortField = 'createdAt' // 上架时间排序
    }

    const res = await getProductList({
      name: searchForm.name,
      category: searchForm.category,
      status: '在售',
      page: searchForm.page,
      limit: searchForm.limit,
      sort: sortField || undefined,
      order: sortField ? sortOrder.value : undefined,
    })

    if (res.code === 200 && res.data) {
      const newProducts = res.data.list || []
      total.value = res.data.total || 0

      productList.value.push(...newProducts)
      searchForm.page++

      // 判断是否已加载完所有数据
      if (productList.value.length >= total.value) {
        finished.value = true
      }
    } else {
      finished.value = true
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    finished.value = true
  } finally {
    loading.value = false
  }
}

// 刷新
const onRefresh = () => {
  searchForm.page = 1
  finished.value = false
  onLoad()
}

// 跳转到商品详情
const goToProductDetail = (id: number) => {
  router.push(`/product/${id}`)
}

// 添加到购物车
const addToCart = (product: any) => {
  cartStore.addToCart(product)
  showToast({
    message: '已加入购物车',
    icon: 'cart-o',
  })
}

onMounted(() => {
  if (route.query.keyword) {
    searchForm.name = route.query.keyword as string
  }

  if (route.query.category) {
    searchForm.category = route.query.category as string
  }

  onLoad()
})
</script>

<style scoped lang="scss">
.product-list-container {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 50px;
}

.search-header {
  position: sticky;
  top: 0;
  z-index: 100;
}

.filter-bar {
  display: flex;
  justify-content: space-around;
  background-color: $white;
  padding: $padding-xs 0;
  border-bottom: 1px solid #f5f5f5;

  .filter-item {
    display: flex;
    align-items: center;
    font-size: $font-size-md;
    color: $text-color;

    span {
      margin-right: $padding-xs;

      &.active {
        color: $primary-color;
        font-weight: 500;
      }
    }
  }
}

.product-list {
  padding: $padding-xs;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: $padding-xs;
}

.product-card {
  background-color: $white;
  border-radius: $border-radius-md;
  overflow: hidden;
  margin-bottom: $padding-xs;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .product-img {
    width: 100%;
    height: 150px;
    object-fit: cover;
  }

  .product-info {
    padding: $padding-sm;

    .product-name {
      font-size: $font-size-md;
      color: $text-color;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: $padding-xs;
    }

    .product-price {
      font-size: $font-size-md;
      color: $primary-color;
      font-weight: 500;
      margin-bottom: $padding-xs;
    }

    .product-action {
      display: flex;
      justify-content: flex-end;
    }
  }
}

.category-popup {
  padding: $padding-md;

  .popup-title {
    text-align: center;
    font-size: $font-size-lg;
    font-weight: 500;
    margin-bottom: $padding-md;
  }

  .category-list {
    display: flex;
    flex-wrap: wrap;

    .category-item {
      width: 33.33%;
      padding: $padding-sm;
      text-align: center;
      font-size: $font-size-md;
      color: $text-color;
      border-radius: $border-radius-md;
      margin-bottom: $padding-sm;

      &.active {
        color: $primary-color;
        background-color: rgba($primary-color, 0.1);
        font-weight: 500;
      }
    }
  }
}
</style> 